<template>
    <div v-loading="loading">
        <b-table
            ref="table"
            :columns="columns"
            :scroll="{ x: 1300 }"
            :request="loadData"
            :export-config="{ use: true, select: '物资设备采购策划表导出选中', all: '物资设备采购策划表导出全部' }"
        >
            <template slot="prefix" slot-scope="ref">
                <template v-if="state !== 3">
                    <a-button icon="plus" type="primary" @click="openDialog(0)"> 添加行 </a-button>
                    <a-button icon="delete" @click="ref.delete(delFuc)"> 删除行 </a-button>
                </template>
            </template>
            <template slot="suffix">
                <template v-if="state !== 3">
                    <ExportExcel
                        ref="exportExcel"
                        :export-list="exportList"
                        file-name="物资设备采购策划表模板.xlsx"
                        button-text="标准模板下载"
                        @click="openDialog(1)"
                    />
                    <ExcelImportButton
                        :loading="loadingImport"
                        icon="import"
                        button-text="批量导入"
                        @handleSubmit="handleImport"
                    />
                </template>
            </template>
            <span slot="index" slot-scope="text, record, index">{{ index + 1 }}</span>
            <template
                v-for="(col, num) in [
                    'purchaseTypeStr',
                    'chargePerson',
                    'planTime',
                    'productionCycle',
                    'materailsApproachTime',
                    'materailsApproachPerson',
                    'materailsBiddingTime',
                    'materailsBiddingPerson',
                    'brandOwnersConfirmTime',
                    'brandOwnersConfirmPerson',
                    'demandPlanTime',
                    'demandPlanPerson',
                    'riskAnalysis',
                    'riskIdentification',
                    'countermeasures',
                    'apartyPrice',
                    'cost',
                    'priceDifference',
                    'quantityDifference',
                    'totalBenefit',
                    'benefitRate',
                    'remark'
                ]"
                :slot="col"
                slot-scope="text, record, index"
            >
                <div :key="num" :class="{ 'form-item': col !== 'remark' }">
                    <template v-if="state != 3">
                        <a-select
                            v-if="col === 'purchaseTypeStr'"
                            v-model="record['purchaseType']"
                            v-check="'purchaseType'"
                            @change="
                                save(record, () => {
                                    setPurchaseTypeStr(record)
                                })
                            "
                        >
                            <a-select-option v-for="item in optionArr" :key="item.id" :value="item.id">
                                {{ item.name }}
                            </a-select-option>
                        </a-select>
                        <a-input-search
                            v-else-if="col === 'chargePerson'"
                            v-model="record[col]"
                            v-check="col"
                            placeholder="请选择"
                            @search="openTotalPerson(index)"
                            @click="openTotalPerson(index)"
                        />
                        <a-date-picker
                            v-else-if="col === 'planTime'"
                            v-model="record[col]"
                            v-check="col"
                            value-format="YYYY-MM-DD"
                            @change="save(record)"
                        />
                        <a-date-picker
                            v-else-if="col === 'materailsApproachTime'"
                            v-model="record[col]"
                            v-check="col"
                            value-format="YYYY-MM-DD"
                            @change="save(record)"
                        />
                        <a-input-search
                            v-else-if="col === 'materailsApproachPerson'"
                            v-model="record[col]"
                            v-check="col"
                            placeholder="请选择"
                            @search="openInPerson(index)"
                            @click="openInPerson(index)"
                        />
                        <a-date-picker
                            v-else-if="col === 'materailsBiddingTime'"
                            v-model="record[col]"
                            v-check="col"
                            value-format="YYYY-MM-DD"
                            @change="save(record)"
                        />
                        <a-input-search
                            v-else-if="col === 'materailsBiddingPerson'"
                            v-model="record[col]"
                            v-check="col"
                            placeholder="请选择"
                            @search="openTenderPerson(index)"
                            @click="openTenderPerson(index)"
                        />
                        <a-date-picker
                            v-else-if="col === 'brandOwnersConfirmTime'"
                            v-model="record[col]"
                            v-check="col"
                            value-format="YYYY-MM-DD"
                            @change="save(record)"
                        />
                        <a-input-search
                            v-else-if="col === 'brandOwnersConfirmPerson'"
                            v-model="record[col]"
                            v-check="col"
                            placeholder="请选择"
                            @search="openBrandPerson(index)"
                            @click="openBrandPerson(index)"
                        />
                        <a-date-picker
                            v-else-if="col === 'demandPlanTime'"
                            v-model="record[col]"
                            v-check="col"
                            value-format="YYYY-MM-DD"
                            @change="save(record)"
                        />
                        <a-input-search
                            v-else-if="col === 'demandPlanPerson'"
                            v-model="record[col]"
                            v-check="col"
                            placeholder="请选择"
                            @search="openCompilePerson(index)"
                            @click="openCompilePerson(index)"
                        />
                        <b-input-number
                            v-else-if="
                                col === 'productionCycle' ||
                                col === 'apartyPrice' ||
                                col === 'cost' ||
                                col === 'quantityDifference'
                            "
                            v-model="record[col]"
                            v-check="col"
                            :min="0"
                            :precision="2"
                            @blur="save(record)"
                        />
                        <b-input-number
                            v-else-if="col === 'benefitRate'"
                            v-model="record[col]"
                            v-check="col"
                            :min="0"
                            :precision="2"
                            @blur="save(record)"
                        />
                        <b-input-number
                            v-else-if="col === 'priceDifference' || col === 'totalBenefit'"
                            v-model="record[col]"
                            v-check="col"
                            :precision="2"
                            @blur="save(record)"
                        />
                        <BaseInput v-else v-model="record[col]" v-check="col" @blur="save(record)" />
                    </template>
                    <template v-else>
                        {{ text }}
                    </template>
                </div>
            </template>
        </b-table>
        <!-- 物料目录选择 -->
        <select-material-dir
            :confirm-loading="confirmLoading"
            :visible.sync="visible"
            :exsist-datas="exsistDatas"
            :is-out-selected="openDialogType === 0"
            @ok="createList"
        />
        <!-- 总责任人 -->
        <person-list ref="totalPersonList" @getPerson="getTotalPerson" />
        <!-- 物资进场责任人 -->
        <person-list ref="inPersonList" @getPerson="getInPerson" />
        <!-- 品牌业主确认责任人 -->
        <person-list ref="brandPersonList" @getPerson="getBrandPerson" />
        <!-- 物资招标责任人 -->
        <person-list ref="tenderPersonList" @getPerson="getTenderPerson" />
        <!-- 需求计划编制责任人 -->
        <person-list ref="compilePersonList" @getPerson="getCompilePerson" />
    </div>
</template>
<script>
import { materialColumns, formData } from './insideModel'
import { findCatalogList } from '@/api/material/goods/goods'
import {
    equipmentPurchaseAddList,
    equipmentPurchaseAddListDel,
    equipmentPurchaseBatchAddListCreate,
    equipmentPurchaseAddListEdit
} from '@/api/material/materialMasterPlan/equipmentPurchasePlan'
import { selectOption } from '@/api/material/goods/goods'
import SelectMaterialDir from '@/components/Dialog/SelectMaterialDir'
import ExportExcel from '@/components/exportExcel/ExportExcel'
const data = []
export default {
    name: 'MaterialPlan',
    components: { SelectMaterialDir, ExportExcel },
    props: {
        projectId: {
            type: String,
            default: ''
        },
        state: {
            type: Number
        },
        version: {
            type: String,
            default: ''
        },
        id: {
            type: String
        }
    },
    data() {
        this.cacheData = data.map((item) => ({ ...item }))
        return {
            loadData: (params) => equipmentPurchaseAddList({ ...params, materialPurchaseId: this.id }),
            delFuc: equipmentPurchaseAddListDel,
            loading: false,
            loadingImport: false, //批量导入按钮loading
            confirmLoading: false, //确认按钮loading
            projectID: null, // 项目编码
            columns: materialColumns.filter((i) => !i.isHidden),
            formData: formData,
            optionArr: [],
            rules: {
                // purchaseTypeStr: { rule: 'required', message: '采购方式不能为空' },
                purchaseType: { rule: 'required', message: '采购方式不能为空' },
                chargePerson: { rule: 'required', message: '总责任人不能为空' },
                planTime: { rule: 'required', message: '计划时间不能为空' },
                productionCycle: { rule: 'required', message: '产运周期（天）不能为空' },
                materailsApproachTime: { rule: 'required', message: '物资进场最迟时间不能为空' },
                materailsApproachPerson: { rule: 'required', message: '物资进场责任人不能为空' },
                materailsBiddingTime: { rule: 'required', message: '物资招标最迟时间不能为空' },
                materailsBiddingPerson: { rule: 'required', message: '物资招标责任人不能为空' },
                brandOwnersConfirmTime: { rule: 'required', message: '品牌业主确认最迟时间不能为空' },
                brandOwnersConfirmPerson: { rule: 'required', message: '品牌业主确认责任人不能为空' },
                demandPlanTime: { rule: 'required', message: '需求计划编制最迟时间不能为空' },
                demandPlanPerson: { rule: 'required', message: '需求计划编制责任人不能为空' },
                riskAnalysis: { rule: 'required', message: '风险源分析不能为空' },
                riskIdentification: { rule: 'required', message: '风险辨识不能为空' },
                countermeasures: { rule: 'required', message: '应对措施不能为空' },
                apartyPrice: { rule: 'required', message: '甲方认价（元）不能为空' },
                cost: { rule: 'required', message: '成本（元）不能为空' },
                priceDifference: { rule: 'required', message: '价差效益（元）不能为空' },
                quantityDifference: { rule: 'required', message: '量差效益（元）不能为空' },
                totalBenefit: { rule: 'required', message: '效益总额（元）不能为空' },
                benefitRate: { rule: 'required', message: '效益率（%）不能为空' }
            },
            editingIndex: null,
            checkKeys: new Map(),
            importCheck: {
                二级物资目录: 'secondaryMaterialList',
                目录编码: 'materialCode',
                '*采购方式': 'purchaseType', // 采购方式
                '*总责任人': 'chargePerson', // 总责任人
                '*总责任人电话': 'chargePersonPhone', // 总责任人
                '*计划时间': 'planTime', // 计划时间
                '*产运周期（天）': 'productionCycle', // 产运周期（天）
                '*物资进场最迟时间': 'materailsApproachTime', // 物资进场最迟时间
                '*物资招标最迟时间': 'materailsBiddingTime', // 物资招标最迟时间
                '*物资进场责任人': 'materailsApproachPerson', // 物资进场责任人
                '*物资进场责任人电话': 'materailsApproachPersonPhone', // 物资进场责任人电话
                '*物资招标责任人': 'materailsBiddingPerson', // 物资招标责任人
                '*物资招标责任人电话': 'materailsBiddingPersonPhone', // 物资招标责任人电话
                '*品牌业主确认最迟时间': 'brandOwnersConfirmTime', // 品牌业主确认最迟时间
                '*品牌业主确认责任人': 'brandOwnersConfirmPerson', // 品牌业主确认责任人
                '*品牌业主确认责任人电话': 'brandOwnersConfirmPersonPhone', // 品牌业主确认责任人电话
                '*需求计划编制最迟时间': 'demandPlanTime', // 需求计划编制最迟时间
                '*需求计划编制责任人': 'demandPlanPerson', // 需求计划编制责任人
                '*需求计划编制责任人电话': 'demandPlanPersonPhone', // 需求计划编制责任人电话
                '*风险源分析': 'riskAnalysis', // 风险源分析
                '*风险辨识': 'riskIdentification', // 风险辨识
                '*应对措施': 'countermeasures', // 应对措施
                '*甲方认价（元）': 'apartyPrice', // 甲方认价（元）
                '*成本（元）': 'cost', // 成本（元）
                '*价差效益（元）': 'priceDifference', // 价差效益（元）
                '*量差效益（元）': 'quantityDifference', // 量差效益（元）
                '*效益总额（元）': 'totalBenefit', // 效益总额（元）
                '*效益率（%）': 'benefitRate', // 效益率（%）
                备注: 'remark' // 备注
            },
            openDialogType: 0, // 打开弹窗类型：0 新增；1 模板下载
            exsistDatas: [], // 已存在的物料目录
            visible: false, // 物料目录弹窗控件
            exportList: []
        }
    },
    directives: {
        check: {
            inserted(el, binding, vNode) {
                if (vNode.context.rules[binding.value]) {
                    let rule = vNode.context.rules[binding.value]
                    vNode.context.checkKeys.set(binding.value, rule.message)
                }
            }
        }
    },
    mounted() {
        this.getOption()
    },
    watch: {
        projectId: {
            handler(val) {
                this.projectID = val
            },
            immediate: true
        }
    },
    methods: {
        /**
         * 采购方式的字符串设置
         */
        setPurchaseTypeStr(data) {
            this.optionArr.forEach((item) => {
                if (data.purchaseType === item.id) {
                    data.purchaseTypeStr = item.name
                }
            })
        },
        /**
         * @description: 获取全部列表
         */
        async getAll(callback, errorCallback) {
            let total = this.$refs.table?.totalSize
            if (total > 0) {
                let res = await equipmentPurchaseAddList({
                    pageSize: this.$refs.table?.totalSize,
                    pageNo: 1,
                    materialPurchaseId: this.id
                })
                if (res.code !== this.SUCCESS_CODE) {
                    errorCallback && errorCallback(res)
                    return
                } else {
                    callback && callback(res)
                }
            } else {
                callback && callback({ data: [] })
            }
        },
        /**
         * @description: 打开弹窗
         */
        async openDialog(type) {
            //   新增或下载模板
            this.openDialogType = type
            this.getAll((res) => {
                this.exsistDatas = res.data
                if (type) {
                    this.visible = true
                } else {
                    this.add()
                }
            })
        },
        /**
         * @description: 导入
         * @param {e} 导入列表
         */
        async handleImport(e) {
            let that = this
            let form = []
            that.loadingImport = true
            let messages = []
            for (let m in e) {
                let keys = e[m]
                let listItem = {}
                let msg = `第${Number(m) + 1}行：`
                let msgList = []
                // 校验excel的表头数量
                // console.log(e[m],e[m][index])
                // 校验excel的表头字段
                for (let i in this.importCheck) {
                    let item = this.importCheck[i]
                    if (!keys[i] && !Object.keys(keys).includes(i) && i != '备注') {
                        msgList.push(`${i.replace(/\*/g, '')}不能为空`)
                    } else {
                        listItem[item] = keys[i]
                    }
                }
                msgList.length > 0 && messages.push(<div>{msg + msgList.join('，')}</div>)
                listItem.purchaseType = this.optionArr.find((t) => t.name === listItem.purchaseType)?.id
                listItem.planTime = this.dateFormat(listItem.planTime) // 计划时间
                listItem.materailsApproachTime = this.dateFormat(listItem.materailsApproachTime) // 物资进场最迟时间
                listItem.materailsBiddingTime = this.dateFormat(listItem.materailsBiddingTime) // 物资招标最迟时间
                listItem.brandOwnersConfirmTime = this.dateFormat(listItem.brandOwnersConfirmTime) // 品牌业主确认最迟时间
                listItem.demandPlanTime = this.dateFormat(listItem.demandPlanTime) // 需求计划编制最迟时间
                form.push(listItem)
            }
            if (messages.length > 0) {
                that.loadingImport = false
                let content = messages.map((item) => <div style="width:100%">{item}</div>)
                that.$warning({
                    width: 800,
                    title: '导入失败',
                    content: content
                })
                return
            }
            const res = await findCatalogList({ commonStatus: 1, leaf: 3, pageNo: 1, pageSize: 10000 })
            // console.log(res)
            if (res.code === this.SUCCESS_CODE) {
                for (let idx in form) {
                    let findItem = res.data.find((q) => q.mateClassName === form[idx].secondaryMaterialList)
                    console.log(findItem,'findItem')
                    form[idx] = Object.assign(
                        {},
                        {
                            materialPurchaseId: this.id,
                            materialCode: findItem?.mateClassCode,
                            materialId: findItem?.id
                        },
                        form[idx]
                    )
                }
                console.log(form)
            } else {
                that.loadingImport = false
                return
            }
            // 发送请求
            equipmentPurchaseBatchAddListCreate(form)
                .then((res) => {
                    that.loadingImport = false
                    if (res.code === 200) {
                        that.$message.success('导入成功！')
                        that.$refs.table.getData()
                    }
                })
                .catch(() => {
                    that.loadingImport = false
                })
        },
        dateFormat(e) {
            // return this.$dateFormat(new Date(e.setDate(e.getDate() - 1)), 'D')
            return this.$dateFormat(new Date(e), 'D')
        },
        add() {
            if (this.editingIndex !== null) {
                return this.$noticeWarning('请结束当前行！')
            }
            this.visible = true
        },
        openTotalPerson(index) {
            this.editingIndex = index
            this.$refs.totalPersonList.open()
        },
        getTotalPerson(row) {
            this.$refs.table.tableData[this.editingIndex]['chargePerson'] = row.name
            this.save(this.$refs.table.tableData[this.editingIndex])
        },
        openInPerson(index) {
            this.editingIndex = index
            this.$refs.inPersonList.open()
        },
        getInPerson(row) {
            this.$refs.table.tableData[this.editingIndex]['materailsApproachPerson'] = row.name
            this.save(this.$refs.table.tableData[this.editingIndex])
        },
        openBrandPerson(index) {
            this.editingIndex = index
            this.$refs.brandPersonList.open()
        },
        getBrandPerson(row) {
            this.$refs.table.tableData[this.editingIndex]['brandOwnersConfirmPerson'] = row.name
            this.save(this.$refs.table.tableData[this.editingIndex])
        },
        openTenderPerson(index) {
            this.editingIndex = index
            this.$refs.tenderPersonList.open()
        },
        getTenderPerson(row) {
            this.$refs.table.tableData[this.editingIndex]['materailsBiddingPerson'] = row.name
            this.save(this.$refs.table.tableData[this.editingIndex])
        },
        openCompilePerson(index) {
            this.editingIndex = index
            this.$refs.compilePersonList.open()
        },
        getCompilePerson(row) {
            this.$refs.table.tableData[this.editingIndex]['demandPlanPerson'] = row.name
            this.save(this.$refs.table.tableData[this.editingIndex])
        },
        getOption() {
            selectOption({ type: 1 }).then((res) => {
                if (res.code === 200) {
                    this.optionArr = res.data
                    this.formData.purchaseType = null
                }
            })
        },
        async createList(selectRows) {
            let form = this.$clone(selectRows)
            if (this.openDialogType) {
                form.forEach((item) => {
                    item.secondaryMaterialList = item.mateClassName
                    item.materialPurchaseId = this.id
                    item.materialCode = item.mateClassCode
                    item.materialId = item.id
                    delete item.id
                })
                let columns = this.$clone(materialColumns)
                columns.forEach((i, num) => {
                    if (num !== 0 && num !== 1 && num !== 2 && num !== 29) {
                        i.title = '*' + i.title
                    }
                })
                // 导出模板配置
                this.exportList = [
                    {
                        columns: columns,
                        datas: form
                    }
                ]
                this.exportList[0].columns[3].options = this.optionArr.map((item) => item.name)
                // 导出
                this.$refs.exportExcel.downExcel()
            } else {
                this.confirmLoading = true
                form.forEach((item) => {
                    item.secondaryMaterialList = item.mateClassName
                    item.materialPurchaseId = this.id
                    item.materialCode = item.mateClassCode
                    item.materialId = item.id
                    delete item.id
                })
                equipmentPurchaseBatchAddListCreate(form)
                    .then((res) => {
                        this.confirmLoading = false
                        if (res.code === 200) {
                            this.visible = false
                            this.cancel()
                        }
                    })
                    .catch(() => {
                        this.confirmLoading = false
                    })
            }
        },
        async save(row, callback) {
            try {
                callback && callback()
                // this.checkKeys.forEach((value, key) => {
                //   if (this.$isEmpty(row[key])) throw new Error(value)
                // })
                // this.loading = true
                let res = await equipmentPurchaseAddListEdit(row)
                if (res.code === this.SUCCESS_CODE) {
                    // this.$message.success('保存成功')
                    this.editingIndex = null
                    // this.cancel()
                }
                // this.loading = false
            } catch (e) {
                this.$noticeWarning(e.message)
            }
        },
        cancel() {
            this.editingIndex = null
            this.$refs.table.getData(null, true)
        }
    }
}
</script>

<style lang="less" scoped>
/deep/ .form-item {
    .ant-input:not([disabled]),
    .ant-time-picker-input,
    .ant-select:not(.ant-select-disabled) .ant-select-selection,
    .ant-calendar-picker-input,
    .ant-input-number-input,
    .ant-cascader-picker {
        border-color: #e4ac0b;
        background-color: #fff9e8;
    }
}
</style>
